﻿using System;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using System.ComponentModel;
using System.Windows.Resources;
using System.IO;
using System.Text;
using Microsoft.Phone.Tasks;
using System.Xml.Linq;
using System.Windows.Navigation;

namespace UI
{
    public partial class Authentication : PhoneApplicationPage
    {
        private bool isLogined = false;

        public Authentication()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            ConfigHelper.IsValidSettings = false;
            this.webBrowser.Navigate(new Uri(ConfigHelper.AuthorizeAPI.APIUrl));
        }

        private void webBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            if (e.Uri.AbsoluteUri == "http://installcertificate/")
            {
                WebBrowserTask task = new WebBrowserTask();
                task.Uri = new Uri(ConfigHelper.CertificateUrl);
                task.Show();

                throw new Exception("Exit");
            }

            if (e.Uri.AbsoluteUri.StartsWith("http://www.localhost.com") == true)
            {
                e.Cancel = true;
                if (e.Uri.AbsoluteUri.Contains("access_denied") == true)
                {
                    throw new Exception("Exit");
                }
                else
                {
                    isLogined = true;
                    this.webBrowser.Navigating -= webBrowser_Navigating;
                    this.webBrowser.Visibility = System.Windows.Visibility.Collapsed;
                    this.loadingIndicator.Begin();

                    string[] queryStrings = e.Uri.AbsoluteUri.Substring(e.Uri.AbsoluteUri.IndexOf('#') + 1).Split('&');
                    foreach (string item in queryStrings)
                    {
                        string[] keyValue = item.Split('=');
                        if (keyValue[0] == "access_token")
                        {
                            ConfigHelper.AccessToken = keyValue[1];
                        }
                        if (keyValue[0] == "expires_in")
                        {
                            double seconds = double.Parse(keyValue[1]);
                            ConfigHelper.AccessTokenExpiredTime = DateTimeOffset.Now.AddSeconds(seconds - 1800);
                        }
                    }

                    OAuthHelper.AccessProtectedResource(ConfigHelper.GetUIDAPI, null, GetUIDCompleted, null);
                }
            }
        }

        private void GetUIDCompleted(HttpWebResponse response, XDocument xmlResult, object userState)
        {
            ConfigHelper.UserId = xmlResult.Root.Element("uid").Value;
            ConfigHelper.IsValidSettings = true;

            this.Dispatcher.BeginInvoke
            (
                () =>
                {
                    this.loadingIndicator.Stop();
                    this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                }
            );
        }

        private void webBrowser_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (isLogined == false)
            {
                e.Handled = true;

                Uri uri = new Uri("InstallCertificate.htm", UriKind.Relative);
                StreamResourceInfo info = Application.GetResourceStream(uri);
                Stream stream = info.Stream;
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, (int)stream.Length);
                string htmlString = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                this.webBrowser.NavigateToString(htmlString);
            }
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
        {
            while (this.NavigationService.CanGoBack == true)
            {
                this.NavigationService.RemoveBackEntry();
            }
        }
    }
}